import httpService, { RequestParam } from './request';
import http from '@ohos.net.http';
import { fileManager } from "../utils/fileUtils"
import { DBtextEmb, simOrig, strCaptions } from '../utils/recallInterface';
import { promptAction } from '@kit.ArkUI';

let ADD_URL =
  "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add?access_token=24.91a2d4563f6c563ae88b8bfbbc2a3f24.2592000.1738311063.282335-116458984"
let SEARCH_URL =
  "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search?access_token=24.91a2d4563f6c563ae88b8bfbbc2a3f24.2592000.1738311063.282335-116458984"
// ADD_URL="http://192.168.227.230:5000/post-endpoint"
let TAG = "_:_ImageSim"

export default class ImageSimManager {
  private ImgSimresult
  private requestOptions: http.HttpRequestOptions = {}

  InitParam(imgstr, brief = "") {
    let datastr = 'image=' + encodeURIComponent(imgstr)
    if (brief) {
      datastr += '&brief=' + encodeURIComponent(brief)
    }
    this.requestOptions = {
      method: http.RequestMethod.POST,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      extraData: datastr
    }
  }

  parseAddResult(result): string {
    let TAG = "_:_[parseResultImgSim]"
    console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")) {
      promptAction.showToast({
        "message": result, "duration": 5000
      })
    }
    try {
      let resultj = JSON.parse(result)
      console.error(TAG+"_______", "parse success ", resultj, JSON.stringify(resultj))
      return "success"
    } catch (e) {
      console.error(TAG, "parseResult", e)
      return result
    }
  }

  parseSearchResult(result): simOrig<DBtextEmb>[] {
    let TAG = "_:_[parseResultImgSim]"
    console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")) {
      promptAction.showToast({
        "message": result, "duration": 5000
      })
    }
    try {
      let resultj = JSON.parse(result)
      console.log(TAG, "parse success ", resultj, JSON.stringify(resultj))
      let simorig: simOrig<DBtextEmb>[] = []
      for (let aresult of resultj.result) {
        simorig.push({
          origin: {
            content: "", path: aresult.brief, vec: ""
          },
          sim: aresult.score,
          type:"ImageSim"
        })
      }
      return simorig
    } catch (e) {
      console.error(TAG, "parseResult", e)
      return result
    }
  }

  async add(imgstr, brief): Promise<string> {
    this.InitParam(imgstr, brief)
    return await httpService.requestMain(ADD_URL, this.requestOptions, (response) => {
      return this.parseAddResult(response)
    })
  }

  async search(imgstr): Promise<simOrig<DBtextEmb>[]> {
    this.InitParam(imgstr)
    return await httpService.requestMain(SEARCH_URL, this.requestOptions, (response) => {
      return this.parseSearchResult(response)
    })
  }
}